import React, { Component } from 'react';
import GridTable from '../components/display/gridTable';
import ScModal from '../components/feedback/scModal';
import { Button, Input, message, Modal,Row,Col } from 'antd';
import Transfer from 'antd/lib/transfer';
import { getUserList, getDDuserList, addUser, getRoleList, distributeRole, getUserMenuList, userDelete} from '../fetch/fetchApi';
import '../assets/stylus/com/dataentry/transfer.styl';
import PropTypes from "prop-types";
const Search = Input.Search;

class Home extends Component {
    constructor() {
        super();
        this.init();
        this.noData = {
            emptyText: '暂无数据'
        };
        this.state = {
            gridData: null,
            modalVisible: !1,
            modalTitle: '',
            confirmLoading: !1,
            menuList: [],
            fromData: [],
            defaultTarget: [],
            inputValue: '',
            defaultTitle: '',
            defaultType: undefined,
            listData: [],
            width: 800,
            loading: !1,
            showFlag: !0,
            pagination: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 10,
                onChange: this.tableChange.bind(this)
            },
            pagination1: {
                current: 1,
                defaultCurrent: 1,
                defaultPageSize: 6,
                onChange: this.tableChange1.bind(this)
            }
        }
    }

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    tableChange(e) {
        const page = {
            ...this.state.pagination
        };
        page.current = e;
        this.setState({
            pagination: page
        });
    }

    tableChange1(e) {
        const page = {
            ...this.state.pagination1
        };
        page.current = e;
        this.setState({
            pagination1: page
        });
    }

    static contextTypes = {
        router: PropTypes.object.isRequired
    }

    init() {
        this.title = '用户管理';
        this.subTitle = '用户列表';
        /*this.selectedKey = ['0001'];
        this.openKeys = ['00'];*/
        this.query={};
        this.tableColumns = [
            {
                title: '用户名称',
                dataIndex: 'name',
                key: 'name',
            }, {
                title: '用户电话',
                dataIndex: 'phone',
                key: 'phone',
            }, {
                title: '用户邮箱',
                dataIndex: 'email',
                key: 'email',
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <div className="action-wrap">
                        <Button type="primary"
                    id={record.key}
                    title="分配角色"
                    index={record.index}
                    paramstr={record.paramStr}
                    onClick={this.dispathRole.bind(this)}>分配角色</Button>
                        <Button type="primary"
                    id={record.key}
                    title="删除"
                    onClick={(e) => this.confirm(record.key)}>删除</Button>
                    </div>
                )
            }
        ];
        this.searchColumns = [
            {
                title: '用户名称',
                dataIndex: 'name',
                key: 'name',
            }, {
                title: '电话',
                dataIndex: 'phone',
                key: 'phone',
            }, {
                title: '邮箱',
                dataIndex: 'email',
                key: 'email',
            }, {
                title: '操作',
                key: 'action',
                render: (text, record, index) => (
                    <div className="action-wrap">
                <Button type="primary"
                    id={record.key}
                    title="添加"
                    index={index}
                    onClick={this.addUser.bind(this)}>添加</Button>
              </div>
                )
            }];
    }

    componentWillMount() {
        this.params = {};
        this.getUserListCb();
        this.getRoleList();
        this.getUserMenuList();
    }

    confirm=(key) => {
        Modal.confirm({
            title: 'Confirm',
            content: '确定删除该条数据？',
            okText: '确认',
            cancelText: '取消',
            onOk: (e) => {
                return this.deleteItem(key).then((res) => {
                    if (res && res.data && res.data.code === "200") {
                        message.success("删除成功！");
                        this.getUserListCb();
                    }
                })
            }
        });
    }

    async deleteItem(key) {
        console.log(key);
        return await userDelete({
            uid: key
        })
    }

    getUserListCb() {
        this.getUserList().then(() => {
            this.setState({
                loading: !1
            });
        });
    }

    async getRoleList() {
        try {
            const resData = await getRoleList();
            let fromData = resData.data.data;
            fromData = JSON.parse(JSON.stringify(fromData).replace(/id/g, 'key').replace(/childList/g, 'children'));
            this.setState({
                modalVisible: !1,
                fromData
            });
        } catch ( e ) {
            console.log(e);
        }
    }

    async getUserList() {
        this.setState({
            loading: !0
        });
        try {
            const resData = await getUserList(this.query);
            let gridData = resData.data.data||[];
            for ( let i of gridData ) {
                i.name || (i.name = '--');
                i.phone || (i.phone = '--');
                i.email || (i.email = '--');
            }
            const page = {
                ...this.state.pagination
            };
            page.total = gridData.length;
            this.setState({
                modalVisible: !1,
                gridData,
                pagination: page
            });
        } catch ( e ) {
            console.log(e);
        }
    }

    openNewRole(e) {
        this.setState({
            width: 800,
            modalVisible: !0,
            showFlag: !0,
            modalTitle: e.target.title,
            roleId: e.target.id
        });
    }

    onSearch(e) {
        this.getDDuserList(e);
    }

    async getDDuserList(name) {
        name.trim().length === 0 && this.setState({
            listData: []
        });
        try {
            const resData = await getDDuserList({
                name
            });
            if (resData.data.code === '200') {
                const userInfo = resData.data.data;
                this.setState({
                    listData: userInfo
                });
            }
        } catch ( e ) {
            console.log(e);
        }
    }

    async addUser(e) {
        try {
            const resData = await addUser(this.state.listData[e.target.getAttribute('index')]);
            if (resData.data.code === '200') {
                this.setState({
                    listData: []
                });
                this.getUserListCb();
            }
        } catch ( e ) {
            console.log(e);
        }
    }

    dispathRole(e) {
        this.setState({
            modalVisible: !0,
            width: 520,
            showFlag: !1,
            modalTitle: e.target.title,
            userId: e.target.id,
            defaultTarget: e.target.getAttribute('paramStr') ? e.target.getAttribute('paramstr').split(',') : [],
        });
    }

    async distributeRole() {
        this.setState({
            confirmLoading: !0
        });
        try {
            const resData = await distributeRole({
                userId: this.state.userId,
                roleIds: this.params.roleIds
            });
            this.setState({
                confirmLoading: !1
            });
            resData.data.code === '200' && (this.getUserListCb(), this.getUserMenuList());
        } catch ( e ) {
            console.log(e);
        }
    }

    handleTransferChange(target) {
        this.setState({
            defaultTarget: target
        });
        this.params.roleIds = target.length ? target.join(',') : '';
    }

    filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
    }

    cancel() {
        this.setState({
            modalVisible: !1
        });
    }

    async getUserMenuList() {
        try {
            const resData = await getUserMenuList();
            this.setState({
                'menuList': resData.data.data
            })
        } catch ( e ) {
            console.log(e);
        }
    }

    handleNameInputChange=(e)=>{
        this.query.name=e.target.value;
    }

    handleQueryBtnClick=()=>{
        this.getUserListCb();
    }

    render() {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col span={3}>
                        <Input placeholder="用户名称" onChange={this.handleNameInputChange}/>
                    </Col>
                    <Col lg={2} xl={1} className={'whole-fill'}>
                        <Button type="primary" onClick={this.handleQueryBtnClick}>查询</Button>
                    </Col>
                    <Col lg={3} xl={2} className={'whole-fill'}>
                        <Button type="primary"
                            title="添加用户"
                            deftitle=""
                            deftype = ""
                            onClick={this.openNewRole.bind(this)}>
                            添加用户
                        </Button>
                    </Col>
                </Row>
                
            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.gridData} loading={this.state.loading} columns={this.tableColumns} pagination={this.state.pagination}/>
            </div>
        </div>;
        return <div>
          {Content}
            {this.state.showFlag ? <ScModal
            width={this.state.width}
            modalVisible={this.state.modalVisible}
            modalTitle={this.state.modalTitle}
            modalContent={<div>
                    <div className="modal-list">
                        <Search
            placeholder="请先查询用户名称"
            onSearch={this.onSearch.bind(this)}
            />
                    </div>
                    <div className="modal-list">
                        <GridTable postyle="table-center" data={this.state.listData} columns={this.searchColumns} pagination={this.state.pagination1} locale={this.noData}/>
                    </div>
                </div>}
            cancel = {this.cancel.bind(this)}
            footer={null}
            param = {this.params}
            /> : <ScModal
            width={this.state.width}
            modalVisible={this.state.modalVisible}
            modalTitle={this.state.modalTitle}
            modalContent={<div><div className="modal-list">
              <Transfer
            dataSource={this.state.fromData}
            showSearch
            titles={['所有角色', '已选角色']}
            searchPlaceholder="请输入角色"
            notFoundContent="暂无角色数据"
            itemUnit = "条"
            targetKeys={this.state.defaultTarget}
            onChange={this.handleTransferChange.bind(this)}
            render={item => item.title}
            />
            </div></div>}
            handle = {this.distributeRole.bind(this)}
            cancel = {this.cancel.bind(this)}
            confirmLoading={this.state.confirmLoading}
            param = {this.params}
            />}
        </div>
    }
}

export default Home;